package servlet;

import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet(urlPatterns = { "/Event", "/event", "/EventServlet", "/eventServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class EventServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public EventServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<EventModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				getServletContext().getRequestDispatcher("/eventNew.jsp").forward(request, response);
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			EventModel query = new EventModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<EventModel, EventModelExt> dal = new GenericDal<EventModel, EventModelExt>(new EventModel());

			EventModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("event", obj);
				getServletContext().getRequestDispatcher("/eventEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			EventModel query = new EventModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<EventModel, EventModelExt> dal = new GenericDal<EventModel, EventModelExt>(new EventModel());

			EventModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("event", obj);
				getServletContext().getRequestDispatcher("/eventView.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			EventModel obj = new EventModel();

			// TODO set name here

			GenericDal<EventModel, EventModelExt> dal = new GenericDal<EventModel, EventModelExt>(new EventModel());

			int res = 0;
			try {
				res = dal.insert(obj);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("delete")) {

			EventModel query = new EventModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<EventModel, EventModelExt> dal = new GenericDal<EventModel, EventModelExt>(new EventModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect("eventList.jsp");
				//getServletContext().getRequestDispatcher("/eventList.jsp").forward(request, response);
			} else {
				// TODO fail
			}
		} else if (mode.equalsIgnoreCase("getCascadeDropdowList")){
			response.setContentType("text/xml; charset=UTF-8");
			String idProject=request.getParameter("idParent");
			
			try{
			List<EventModel> list = CacheUtil.getEventList(Integer.parseInt(idProject));
			List<String> listEvent = new ArrayList<String>();
			List<String> listEventId = new ArrayList<String>();
			for(int i=0;i<list.size();i++)
			{
				listEvent.add(i, list.get(i).getName());
				listEventId.add(i, list.get(i).getIdToString());
			}
			PrintWriter out = response.getWriter();
			
			String resultXML = CommonUtil.createAjaxResultXML("quotation", listEvent, listEventId);
			out.println(resultXML);
			}
			catch(Exception e)
			{}
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {

			EventModel obj = new EventModel();

			String id_project = request.getParameter("id_project");
                    if (id_project != null && !id_project.isEmpty()) {
					    obj.setIdProject(Integer.parseInt(id_project));
                    }

String name = request.getParameter("name");
					obj.setName(name);

String code = request.getParameter("code");
					obj.setCode(code);

String description = request.getParameter("description");
					obj.setDescription(description);

//String id_task = request.getParameter("id_task");
//                    if (id_task != null && !id_task.isEmpty()) {
//					    obj.setIdTask(Integer.parseInt(id_task));
//                    }
//
//String id_type = request.getParameter("id_type");
//                    if (id_type != null && !id_type.isEmpty()) {
//					    obj.setIdType(Integer.parseInt(id_type));
//                    }

String id_place = request.getParameter("id_place");
                    if (id_place != null && !id_place.isEmpty()) {
					    obj.setIdPlace(Integer.parseInt(id_place));
                    }

String id_venue = request.getParameter("id_venue");
                    if (id_venue != null && !id_venue.isEmpty()) {
					    obj.setIdVenue(Integer.parseInt(id_venue));
                    }


//String plan_start_time_date = request.getParameter("plan_start_time_date");
//    String plan_start_time_time = request.getParameter("plan_start_time_time");
//    if (plan_start_time_date != null && !plan_start_time_date.isEmpty() && plan_start_time_time != null && !plan_start_time_time.isEmpty()) {
//            obj.setPlanStartTime(DateTimeUtil.parseDateTime(plan_start_time_date, plan_start_time_time));
//} else {
//    obj.setPlanStartTime(DateTimeUtil.parseDate(plan_start_time_date));
//}
//
//
//String plan_end_time_date = request.getParameter("plan_end_time_date");
//    String plan_end_time_time = request.getParameter("plan_end_time_time");
//    if (plan_end_time_date != null && !plan_end_time_date.isEmpty() && plan_end_time_time != null && !plan_end_time_time.isEmpty()) {
//            obj.setPlanEndTime(DateTimeUtil.parseDateTime(plan_end_time_date, plan_end_time_time));
//} else {
//    obj.setPlanEndTime(DateTimeUtil.parseDate(plan_end_time_date));
//}
//
//
//String real_start_tate_date = request.getParameter("real_start_tate_date");
//    String real_start_tate_time = request.getParameter("real_start_tate_time");
//    if (real_start_tate_date != null && !real_start_tate_date.isEmpty() && real_start_tate_time != null && !real_start_tate_time.isEmpty()) {
//            obj.setRealStartTate(DateTimeUtil.parseDateTime(real_start_tate_date, real_start_tate_time));
//} else {
//    obj.setRealStartTate(DateTimeUtil.parseDate(real_start_tate_date));
//}
//
//
//String real_end_time_date = request.getParameter("real_end_time_date");
//    String real_end_time_time = request.getParameter("real_end_time_time");
//    if (real_end_time_date != null && !real_end_time_date.isEmpty() && real_end_time_time != null && !real_end_time_time.isEmpty()) {
//            obj.setRealEndTime(DateTimeUtil.parseDateTime(real_end_time_date, real_end_time_time));
//} else {
//    obj.setRealEndTime(DateTimeUtil.parseDate(real_end_time_date));
//}
//
//String need_approval = request.getParameter("need_approval");
//					obj.setNeedApproval(need_approval.equalsIgnoreCase("true")
//							|| need_approval.equalsIgnoreCase("1"));
//
//String is_event = request.getParameter("is_event");
//					obj.setIsEvent(is_event.equalsIgnoreCase("true")
//							|| is_event.equalsIgnoreCase("1"));
//
//String status = request.getParameter("status");
//                    if (status != null && !status.isEmpty()) {
//					    obj.setStatus(Integer.parseInt(status));
//                    }
//
//String is_draft = request.getParameter("is_draft");
//					obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//							|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//                    if (notification != null && !notification.isEmpty()) {
//					    obj.setNotification(Integer.parseInt(notification));
//                    }

			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<EventModel, EventModelExt> dal = new GenericDal<EventModel, EventModelExt>(new EventModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, redirect to somewhere
					response.sendRedirect("eventNew.jsp?idProject=" + obj.getIdProjectToString());
					//getServletContext().getRequestDispatcher("/eventNew.jsp").forward(request, response);
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("event", obj);
				getServletContext().getRequestDispatcher("/eventInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			EventModel query = new EventModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<EventModel, EventModelExt> dal = new GenericDal<EventModel, EventModelExt>(new EventModel());

			EventModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				String id_project = request.getParameter("id_project");
                    if (id_project != null && !id_project.isEmpty()) {
					    obj.setIdProject(Integer.parseInt(id_project));
                    }

String name = request.getParameter("name");
					obj.setName(name);

String code = request.getParameter("code");
					obj.setCode(code);

String description = request.getParameter("description");
					obj.setDescription(description);

//String id_task = request.getParameter("id_task");
//                    if (id_task != null && !id_task.isEmpty()) {
//					    obj.setIdTask(Integer.parseInt(id_task));
//                    }
//
//String id_type = request.getParameter("id_type");
//                    if (id_type != null && !id_type.isEmpty()) {
//					    obj.setIdType(Integer.parseInt(id_type));
//                    }

String id_place = request.getParameter("id_place");
                    if (id_place != null && !id_place.isEmpty()) {
					    obj.setIdPlace(Integer.parseInt(id_place));
                    }

String id_venue = request.getParameter("id_venue");
                    if (id_venue != null && !id_venue.isEmpty()) {
					    obj.setIdVenue(Integer.parseInt(id_venue));
                    }


//String plan_start_time_date = request.getParameter("plan_start_time_date");
//    String plan_start_time_time = request.getParameter("plan_start_time_time");
//    if (plan_start_time_date != null && !plan_start_time_date.isEmpty() && plan_start_time_time != null && !plan_start_time_time.isEmpty()) {
//            obj.setPlanStartTime(DateTimeUtil.parseDateTime(plan_start_time_date, plan_start_time_time));
//} else {
//    obj.setPlanStartTime(DateTimeUtil.parseDate(plan_start_time_date));
//}
//
//
//String plan_end_time_date = request.getParameter("plan_end_time_date");
//    String plan_end_time_time = request.getParameter("plan_end_time_time");
//    if (plan_end_time_date != null && !plan_end_time_date.isEmpty() && plan_end_time_time != null && !plan_end_time_time.isEmpty()) {
//            obj.setPlanEndTime(DateTimeUtil.parseDateTime(plan_end_time_date, plan_end_time_time));
//} else {
//    obj.setPlanEndTime(DateTimeUtil.parseDate(plan_end_time_date));
//}
//
//
//String real_start_tate_date = request.getParameter("real_start_tate_date");
//    String real_start_tate_time = request.getParameter("real_start_tate_time");
//    if (real_start_tate_date != null && !real_start_tate_date.isEmpty() && real_start_tate_time != null && !real_start_tate_time.isEmpty()) {
//            obj.setRealStartTate(DateTimeUtil.parseDateTime(real_start_tate_date, real_start_tate_time));
//} else {
//    obj.setRealStartTate(DateTimeUtil.parseDate(real_start_tate_date));
//}
//
//
//String real_end_time_date = request.getParameter("real_end_time_date");
//    String real_end_time_time = request.getParameter("real_end_time_time");
//    if (real_end_time_date != null && !real_end_time_date.isEmpty() && real_end_time_time != null && !real_end_time_time.isEmpty()) {
//            obj.setRealEndTime(DateTimeUtil.parseDateTime(real_end_time_date, real_end_time_time));
//} else {
//    obj.setRealEndTime(DateTimeUtil.parseDate(real_end_time_date));
//}
//
//String need_approval = request.getParameter("need_approval");
//					obj.setNeedApproval(need_approval.equalsIgnoreCase("true")
//							|| need_approval.equalsIgnoreCase("1"));
//
//String is_event = request.getParameter("is_event");
//					obj.setIsEvent(is_event.equalsIgnoreCase("true")
//							|| is_event.equalsIgnoreCase("1"));
//
//String status = request.getParameter("status");
//                    if (status != null && !status.isEmpty()) {
//					    obj.setStatus(Integer.parseInt(status));
//                    }
//
//String is_draft = request.getParameter("is_draft");
//					obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//							|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//                    if (notification != null && !notification.isEmpty()) {
//					    obj.setNotification(Integer.parseInt(notification));
//                    }
				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						response.sendRedirect("eventNew.jsp?idProject=" + obj.getIdProject());
						//getServletContext().getRequestDispatcher("/eventNew.jsp").forward(request, response);
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("event", obj);
					getServletContext().getRequestDispatcher("/eventEdit.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("delete")) {

			EventModel query = new EventModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<EventModel, EventModelExt> dal = new GenericDal<EventModel, EventModelExt>(new EventModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect("eventList.jsp");
				//getServletContext().getRequestDispatcher("/eventList.jsp").forward(request, response);
			} else {
				// TODO fail
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			EventModel obj = new EventModel();

			// TODO set name here

			GenericDal<EventModel, EventModelExt> dal = new GenericDal<EventModel, EventModelExt>(new EventModel());

			int res = 0;
			try {
				res = dal.insert(obj);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}

}